package com.waypolice.common.utils;

import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.URLEncoder;

/**
 * 文件
 * @author wr
 *
 */
public class FileUtils {
	/**
	 * 下载文件时，针对不同浏览器，进行附件名的编码
	 * 
	 * @param filename
	 *            下载文件名
	 * @param agent
	 *            客户端浏览器
	 * @return 编码后的下载附件名
	 * @throws IOException
	 */
	public static String encodeDownloadFilename(String filename, String agent)
			throws IOException {
		if (agent.contains("Firefox")) { // 火狐浏览器
			filename = "=?UTF-8?B?"
					+ new BASE64Encoder().encode(filename.getBytes("utf-8"))
					+ "?=";
			filename = filename.replaceAll("\r\n", "");
		} else { // IE及其他浏览器
			filename = URLEncoder.encode(filename, "utf-8");
			filename = filename.replace("+"," ");
		}
		return filename;
	}
	
	/**
	 * 获取项目路径
	 * @return
	 */
	public static String projectWay(){
		StringBuffer sb  = new StringBuffer();
		sb.append(ReadProperties.class.getResource("/").getPath());
		sb.append("/localpdf/");
		return sb.toString();
	}

	/**
	 * @author:zyp
	 * @description 获取外部订单文件后所放置的本地文件路径
	 * @date: 2018/9/4 18:53
	 * @return
	 */
	public static String getFileMountWay(){
		String projectPath = projectWay();
		projectPath += "fileMount";
		return projectPath;
	}
		
	public static void main(String[] args) {
		String str = projectWay();
		System.out.println(str);
	}

	/**
	 * @author:zyp
	 * @description 文件的IO流拷贝
	 * @date: 2018/9/27 16:19:30
	 * @param fileStr 主文件地址
	 * @param aimFileStr 复制到的文件地址
	 * @return
	 */
	public static boolean IOCopy(String fileStr,String aimFileStr){
		String aimFileDirStr = aimFileStr.substring(0,aimFileStr.lastIndexOf("/"));
		File aimFileDir = new File(aimFileDirStr);
		if(!aimFileDir.exists()){
			aimFileDir.mkdirs();
		}
		boolean flag = false;
		FileInputStream fis = null;
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try{
			File file = new File(fileStr);
			File aimFile = new File(aimFileStr);
			fis = new FileInputStream(file);
			fos = new FileOutputStream(aimFile);
			bis = new BufferedInputStream(fis);
			bos = new BufferedOutputStream(fos);
			byte[] bytes = new byte[1024];
			int len = -1;
			while((len = bis.read(bytes))>0){
				bos.write(bytes, 0, len);
			}
			bos.flush();
			flag = true;
		}catch (FileNotFoundException e){
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}finally {
			IoUtils.closeInputStram(fis,bis);
			IoUtils.closeOutputStram(fos,bos);
		}
		return flag;
	}
}
